package com.ziki.common.util.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * 支持断点续传的FTP实用类
 */
public class FtpUtil {
    /**
     * 下载状态
     */
    public enum DownloadStatus {
        Remote_File_Noexist, Local_Bigger_Remote, Download_From_Break_Success, Download_From_Break_Failed,
        Download_New_Success, Download_New_Failed
    }

    /**
     * 上传状态
     */
    public enum UploadStatus {
        Create_Directory_Fail, Change_Directory_Fail, File_Exits, Remote_Bigger_Local, Upload_From_Break_Failed,
        Delete_Remote_Faild, Create_Directory_Success, Upload_From_Break_Success, Upload_New_File_Success,
        Upload_New_File_Failed
    }

    private final FTPClient ftpClient = new FTPClient();

    private boolean isPrintCommond = false;

    private boolean isPassiveMode = true;

    private String ftpControlEncoding = "GBK";

    private ProtocolCommandListener cmdListener = null;

    public FtpUtil() {
    }

    /**
     * 是否在控制台打印FTP输出
     * 
     * @param isPrint
     */
    private void printCommond(boolean isPrint) {
        if (isPrint) {
            if (this.cmdListener == null) {
                this.cmdListener = new PrintCommandListener(new PrintWriter(System.out));
            }
            // 设置将过程中使用到的命令输出到控制台
            this.ftpClient.addProtocolCommandListener(this.cmdListener);
        } else {
            if (this.cmdListener != null) {
                // 不在控制台显示命令
                this.ftpClient.removeProtocolCommandListener(this.cmdListener);
            }
        }
    }

    /**
     * 连接到FTP服务器
     * 
     * @param hostname 主机名
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return 是否连接成功
     * @throws IOException
     */
    public boolean connect(String hostname, int port, String username, String password) throws IOException {
        // 连接服务器
        ftpClient.connect(hostname, port);
        // 设置连接编码
        ftpClient.setControlEncoding(ftpControlEncoding);
        // 返回正常状态
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            // 登录FTP
            if (ftpClient.login(username, password)) {
                return true;
            }
        }
        // 状态异常,关闭连接
        disconnect();
        return false;
    }

    /**
     * 判断是否已经连接到FTP
     * 
     * @return
     */
    public boolean isConnected() {
        return this.ftpClient == null ? false : this.ftpClient.isConnected();
    }

    /**
     * 断开与远程服务器的连接
     * 
     * @throws IOException
     */
    public void disconnect() throws IOException {
        if (this.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }

    /**
     * 递归创建远程服务器目录
     * 
     * @param remote 远程服务器文件绝对路径
     * @param isCreate 不存在的文件夹是否要创建
     * @return 进入目录是否成功
     * @throws IOException
     */
    public boolean changeDirecrotys(String remote, boolean isCreate) throws IOException {
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        if (!directory.equalsIgnoreCase("/") && !changeDirectory(directory)) {
            // 如果远程目录不存在，则递归创建远程服务器目录
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = remote.substring(start, end);
                if (!changeDirectory(subDirectory)) {
                    // 不存在则创建目录
                    if (isCreate) {
                        if (makeDirectory(subDirectory)) {
                            changeDirectory(subDirectory);
                        } else {
                            System.out.println("创建目录" + subDirectory + "失败");
                            return false;
                        }
                    } else {
                        System.out.println("进入目录" + subDirectory + "失败");
                        return false;
                    }
                }

                start = end + 1;
                end = directory.indexOf("/", start);

                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 只进入，不创建目录
     * 
     * @param remote
     * @return
     * @throws IOException
     */
    public boolean changeDirecrotys(String remote) throws IOException {
        return changeDirecrotys(remote, false);
    }

    /**
     * 创建不存在的目录
     * 
     * @param remote
     * @return
     * @throws IOException
     */
    public boolean createDirecrotys(String remote) throws IOException {
        return changeDirecrotys(remote, true);
    }

    /**
     * 改变目录
     * 
     * @param directory
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public boolean changeDirectory(String directory) throws IOException, UnsupportedEncodingException {
        String dirName = encode(directory);
        return ftpClient.changeWorkingDirectory(dirName);
    }

    /**
     * 创建目录
     * 
     * @param directory
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public boolean makeDirectory(String directory) throws IOException, UnsupportedEncodingException {
        String dirName = encode(directory);
        return ftpClient.makeDirectory(dirName);
    }

    /**
     * 上传文件到FTP服务器
     * 
     * @param isLocal 本地输入流
     * @param remote 远程文件路径，使用/home/directory1/subdirectory/file.ext或是 http: //www.xxx.org /subdirectory/file.ext
     *            按照Linux上的路径指定方式，支持多级目录嵌套，支持递归创建不存在的目录结构
     * @param isCreateDir 是否创建不存在的目录
     * @return 上传结果
     * @throws IOException
     */
    public UploadStatus upload(InputStream isLocal, String remote, boolean isCreateDir) throws IOException {
        setTransMode();
        // 设置以二进制流的方式传输
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        // 对远程目录的处理
        String remoteFileName = remote;
        if (remote.contains("/")) {
            remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
            // 是否需要创建不存在的目录
            if (isCreateDir) {
                // 进入并创建服务器远程不存在的目录结构，失败直接返回
                if (!createDirecrotys(remote)) {
                    return UploadStatus.Create_Directory_Fail;
                }

            } else {
                // 进入服务器远程目录结构，失败直接返回
                if (!changeDirecrotys(remote)) {
                    return UploadStatus.Change_Directory_Fail;
                }
            }
        }

        // 检查远程是否存在文件
        if (isFileExistOnServer(remoteFileName)) {
            return UploadStatus.File_Exits;
        }
        // 上传文件
        return this.ftpClient.storeFile(remoteFileName, isLocal) ? UploadStatus.Upload_New_File_Success : UploadStatus.Upload_New_File_Failed;
    }

    /**
     * 上传。不创建不存在的目录
     * 
     * @param isLocal
     * @param remote
     * @return
     * @throws IOException
     */
    public UploadStatus upload(InputStream isLocal, String remote) throws IOException {
        return upload(isLocal, remote, false);
    }

    /**
     * 检查远程是否存在文件
     * 
     * @param remoteFileName
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public boolean isFileExistOnServer(String remoteFileName) throws IOException, UnsupportedEncodingException {
        // 检查远程是否存在文件
        FTPFile[] files = ftpClient.listFiles(encode(remoteFileName));
        return files != null && files.length == 1 ? true : false;
    }

    /**
     * 取得使用iso-8859-1编码的字符串
     * 
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    private String encode(String str) throws UnsupportedEncodingException {
        return new String(str.getBytes(ftpControlEncoding), "iso-8859-1");
    }

    /* ================================================= */
    /**
     * 从FTP服务器上下载文件,支持断点续传，上传百分比汇报
     * 
     * @param remote 远程文件路径
     * @param local 本地文件路径
     * @return 上传的状态
     * @throws IOException
     */
    public DownloadStatus download(String remote, String local) throws IOException {
        // 设置传输模式
        setTransMode();
        // 设置以二进制方式传输
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        DownloadStatus result;

        FTPFile[] files = ftpClient.listFiles(encode(remote));
        if (files.length != 1) {
            System.out.println("远程文件不存在");
            return DownloadStatus.Remote_File_Noexist;
        }

        long lRemoteSize = files[0].getSize();
        File f = new File(local);
        // 本地存在文件，进行断点下载
        if (f.exists()) {
            long localSize = f.length();
            // 判断本地文件大小是否大于远程文件大小
            if (localSize >= lRemoteSize) {
                System.out.println("本地文件大于远程文件，下载中止");
                return DownloadStatus.Local_Bigger_Remote;
            }

            // 进行断点续传，并记录状态
            FileOutputStream out = new FileOutputStream(f, true);
            ftpClient.setRestartOffset(localSize);
            InputStream in = ftpClient.retrieveFileStream(encode(remote));
            byte[] bytes = new byte[1024];
            long step = lRemoteSize / 100;
            long process = localSize / step;
            int c;
            while ((c = in.read(bytes)) != -1) {
                out.write(bytes, 0, c);
                localSize += c;
                long nowProcess = localSize / step;
                if (nowProcess > process) {
                    process = nowProcess;
                    if (process % 10 == 0)
                        System.out.println("下载进度：" + process);
                    // TODO 更新文件下载进度,值存放在process变量中
                }
            }
            in.close();
            out.close();
            boolean isDo = ftpClient.completePendingCommand();
            if (isDo) {
                result = DownloadStatus.Download_From_Break_Success;
            } else {
                result = DownloadStatus.Download_From_Break_Failed;
            }
        } else {
            OutputStream out = new FileOutputStream(f);
            InputStream in = ftpClient.retrieveFileStream(encode(remote));
            byte[] bytes = new byte[1024];
            long step = lRemoteSize / 100;
            long process = 0;
            long localSize = 0L;
            int c;
            while ((c = in.read(bytes)) != -1) {
                out.write(bytes, 0, c);
                localSize += c;
                long nowProcess = localSize / step;
                if (nowProcess > process) {
                    process = nowProcess;
                    if (process % 10 == 0)
                        System.out.println("下载进度：" + process);
                    // TODO 更新文件下载进度,值存放在process变量中
                }
            }
            in.close();
            out.close();
            boolean upNewStatus = ftpClient.completePendingCommand();
            if (upNewStatus) {
                result = DownloadStatus.Download_New_Success;
            } else {
                result = DownloadStatus.Download_New_Failed;
            }
        }
        return result;
    }

    /**
     * 上传文件到FTP服务器，支持断点续传
     * 
     * @param local 本地文件名称，绝对路径
     * @param remote 远程文件路径，使用/home/directory1/subdirectory/file.ext或是 http: //www.guihua.org /subdirectory/file.ext
     *            按照Linux上的路径指定方式，支持多级目录嵌套，支持递归创建不存在的目录结构
     * @return 上传结果
     * @throws IOException
     */
    public UploadStatus upload(String local, String remote) throws IOException {
        setTransMode();
        // 设置以二进制流的方式传输
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        UploadStatus result;
        // 对远程目录的处理
        String remoteFileName = remote;
        if (remote.contains("/")) {
            remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
            // 进入服务器远程目录结构，失败直接返回
            if (!changeDirecrotys(remote)) {
                return UploadStatus.Change_Directory_Fail;
            }
        }

        FTPFile[] files = ftpClient.listFiles(encode(remoteFileName));
        if (files.length == 1) {
            long remoteSize = files[0].getSize();
            File f = new File(local);
            long localSize = f.length();
            if (remoteSize == localSize) {
                return UploadStatus.File_Exits;
            } else if (remoteSize > localSize) {
                return UploadStatus.Remote_Bigger_Local;
            }

            // 尝试移动文件内读取指针,实现断点续传
            result = uploadFile(remoteFileName, f, remoteSize);

            // 如果断点续传没有成功，则删除服务器上文件，重新上传
            if (result == UploadStatus.Upload_From_Break_Failed) {
                if (!ftpClient.deleteFile(remoteFileName)) {
                    return UploadStatus.Delete_Remote_Faild;
                }
                result = uploadFile(remoteFileName, f, 0);
            }
        } else {
            result = uploadFile(remoteFileName, new File(local), 0);
        }
        return result;
    }

    /**
     * 上传文件到服务器,新上传和断点续传
     * 
     * @param remoteFile 远程文件名，在上传之前已经将服务器工作目录做了改变
     * @param localFile 本地文件 File句柄，绝对路径
     * @param processStep 需要显示的处理进度步进值
     * @return
     * @throws IOException
     */
    public UploadStatus uploadFile(String remoteFile, File localFile, long remoteSize) throws IOException {
        UploadStatus status;
        // 显示进度的上传
        long step = localFile.length() / 100;
        long process = 0;
        long localreadbytes = 0L;
        RandomAccessFile raf = new RandomAccessFile(localFile, "r");
        OutputStream out = ftpClient.appendFileStream(encode(remoteFile));
        // 断点续传
        if (remoteSize > 0) {
            ftpClient.setRestartOffset(remoteSize);
            process = remoteSize / step;
            raf.seek(remoteSize);
            localreadbytes = remoteSize;
        }
        byte[] bytes = new byte[1024];
        int c;
        while ((c = raf.read(bytes)) != -1) {
            out.write(bytes, 0, c);
            localreadbytes += c;
            if (localreadbytes / step != process) {
                process = localreadbytes / step;
                System.out.println("上传进度:" + process);
                // TODO 汇报上传状态
            }
        }
        out.flush();
        raf.close();
        out.close();
        boolean result = ftpClient.completePendingCommand();
        if (remoteSize > 0) {
            status = result ? UploadStatus.Upload_From_Break_Success : UploadStatus.Upload_From_Break_Failed;
        } else {
            status = result ? UploadStatus.Upload_New_File_Success : UploadStatus.Upload_New_File_Failed;
        }
        return status;
    }

    /**
     * 发送心跳指令,防止服务器连接超时
     * 
     * @return
     * @throws IOException
     */
    public boolean active() throws IOException {
        return ftpClient.sendNoOp();
    }

    public boolean isPrintCommond() {
        return isPrintCommond;
    }

    public void setPrintCommond(boolean isPrintCommond) {
        this.isPrintCommond = isPrintCommond;
        printCommond(isPrintCommond);
    }

    public String getFtpControlEncoding() {
        return ftpControlEncoding;
    }

    /**
     * 设置FTP连接的字符编码（需要在connect前设置），防止中文乱码。默认为GBK <br/>
     * Sets the character encoding used by the FTP control connection.
     * 
     * @param ftpControlEncoding
     */
    public void setFtpControlEncoding(String ftpControlEncoding) {
        this.ftpControlEncoding = ftpControlEncoding;
    }

    public boolean isPassiveMode() {
        return isPassiveMode;
    }

    public void setPassiveMode(boolean isPassiveMode) {
        this.isPassiveMode = isPassiveMode;
    }

    /**
     * 设置传送模式
     */
    private void setTransMode() {
        if (this.isPassiveMode) {
            // 被动模式
            ftpClient.enterLocalPassiveMode();
        } else {
            // 主动模式
            ftpClient.enterLocalActiveMode();
        }
    }
}
